#!/bin/bash

echo "🧹 清理端口占用进程..."

# 查找并终止所有占用3000端口的进程
echo "📡 检查端口3000占用情况..."
PORT_PIDS=$(lsof -ti:3000)

if [ ! -z "$PORT_PIDS" ]; then
    echo "🔍 发现占用端口3000的进程: $PORT_PIDS"
    echo "💀 正在终止这些进程..."
    kill -9 $PORT_PIDS
    sleep 2
    echo "✅ 端口3000已释放"
else
    echo "✅ 端口3000未被占用"
fi

# 查找并终止所有NestJS相关进程
echo "🔍 检查NestJS相关进程..."
NEST_PIDS=$(ps aux | grep -E "(nest\.js|nest start)" | grep -v grep | awk '{print $2}')

if [ ! -z "$NEST_PIDS" ]; then
    echo "🔍 发现NestJS进程: $NEST_PIDS"
    echo "💀 正在终止这些进程..."
    kill -9 $NEST_PIDS
    sleep 2
    echo "✅ NestJS进程已清理"
else
    echo "✅ 没有发现NestJS进程"
fi

# 查找并终止所有npm start:dev进程
echo "🔍 检查npm start:dev进程..."
NPM_PIDS=$(ps aux | grep "npm run start:dev" | grep -v grep | awk '{print $2}')

if [ ! -z "$NPM_PIDS" ]; then
    echo "🔍 发现npm start:dev进程: $NPM_PIDS"
    echo "💀 正在终止这些进程..."
    kill -9 $NPM_PIDS
    sleep 2
    echo "✅ npm start:dev进程已清理"
else
    echo "✅ 没有发现npm start:dev进程"
fi

# 检查并清理PM2进程
echo "🔍 检查PM2进程..."
PM2_APPS=$(pm2 list | grep "text-tags-backend" | wc -l)

if [ "$PM2_APPS" -gt 0 ]; then
    echo "🔍 发现PM2管理的应用"
    echo "💀 正在停止并删除PM2应用..."
    pm2 stop text-tags-backend 2>/dev/null || true
    pm2 delete text-tags-backend 2>/dev/null || true
    echo "✅ PM2应用已清理"
else
    echo "✅ 没有发现PM2管理的应用"
fi

echo "🎉 清理完成！现在可以安全启动服务器了。"
echo "💡 使用命令: npm run start:dev"
